﻿using CommunityToolkit.Mvvm.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Xaml.Behaviors;
using System;
using System.Windows;

namespace MachineVision.Core.Util.Navigation
{
    /// <summary>
    /// 区域导航功能-初始化行为：往DI容器注册一个或多个视图View，以及注册用于存放Region的RegionManager容器
    /// </summary>
    public class NavigateInitializeBehavior : Behavior<Window>
    {
        /// <summary>
        /// 需导航的视图View的类名，用于注入DI容器
        /// 可以同时注册多个View，只需在各自类名中间加上逗号
        /// </summary>
        public string NameOfRegisterView
        {
            get { return (string)GetValue(NameOfRegisterViewProperty); }
            set { SetValue(NameOfRegisterViewProperty, value); }
        }
        public static readonly DependencyProperty NameOfRegisterViewProperty =
            DependencyProperty.Register("NameOfRegisterView", typeof(string), typeof(NavigateInitializeBehavior));


        protected override void OnAttached()
        {
            base.OnAttached();
            ServiceCollection services = new ServiceCollection();
            services.AddSingleton<RegionManager>();//注册用于存放Region的RegionManager容器

            if (!string.IsNullOrEmpty(NameOfRegisterView))
            {
                var splitArray = NameOfRegisterView.Split(',');
                foreach (string item in splitArray)
                {
                    Type type = CommonTool.GetTypeBaseonName(item);
                    if (type != null)
                    {
                        services.AddSingleton(type);
                    }
                }
            }
            Ioc.Default.ConfigureServices(services.BuildServiceProvider());
        }
    }
}